﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Win32;
using System.Runtime.InteropServices;//timer
using System;
using System.Timers;
namespace Playkanaler
{
    public class ScreenSaver
    {
        static System.Timers.Timer aTimer;
        static string initalscreensaverstatus;
        static uint initalexecutionstate = 0;

        [DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
        static extern EXECUTION_STATE SetThreadExecutionState(EXECUTION_STATE flags);
        [Flags]
         enum EXECUTION_STATE : uint
        {
            ES_SYSTEM_REQUIRED = 0x00000001,
            ES_DISPLAY_REQUIRED = 0x00000002,
            ES_AWAYMODE_REQUIRED = 0x00000040,
            // ES_USER_PRESENT = 0x00000004,
            ES_CONTINUOUS = 0x80000000
        }

        static public void Disable()
        {
            //Take care of screen saver
            RegistryKey rkScreenSaver = Registry.CurrentUser.OpenSubKey(@"Control Panel\Desktop", true);
            initalscreensaverstatus = (string)rkScreenSaver.GetValue("ScreenSaveActive");
            if (initalscreensaverstatus != "0")
            {
                rkScreenSaver.SetValue( "ScreenSaveActive", "0" );
            }
            rkScreenSaver.Close();

            //handle power scheme, prevent sleep/monitor off
            initalexecutionstate = (uint)SetThreadExecutionState(EXECUTION_STATE.ES_SYSTEM_REQUIRED | EXECUTION_STATE.ES_CONTINUOUS | EXECUTION_STATE.ES_DISPLAY_REQUIRED);

            if (initalexecutionstate != 0)
            {
                // Create a timer with a ten second interval.
                aTimer = new System.Timers.Timer(10000);

                // Hook up the Elapsed event for the timer.
                aTimer.Elapsed += new ElapsedEventHandler(OnTimedEvent);

                // Set the Interval to 1,5 seconds (1500 milliseconds).
                aTimer.Interval = 1500;
                aTimer.Enabled = true;
            }
        }
        private static void OnTimedEvent(object source, ElapsedEventArgs e)
        {
            SetThreadExecutionState(EXECUTION_STATE.ES_DISPLAY_REQUIRED | EXECUTION_STATE.ES_CONTINUOUS);
        }

        static public void Enable()
        {
            RegistryKey rkScreenSaver = Registry.CurrentUser.OpenSubKey(@"Control Panel\Desktop", true);
            rkScreenSaver.SetValue("ScreenSaveActive", initalscreensaverstatus);
            rkScreenSaver.Close();
            if (initalexecutionstate != 0)
            {
                SetThreadExecutionState((EXECUTION_STATE)initalexecutionstate);
            }            
        }



    }
}
